package com.itcoon.cloud.framework.mybatis.security.handler;

import com.itcoon.cloud.framework.mybatis.metahandler.AbstractMetaObjectHandler;
import com.itcoon.cloud.framework.mybatis.security.core.AuthUser;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.core.Ordered;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Transactional
public class AuthenticateMetaObjectHandler extends AbstractMetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        LocalDateTime now = LocalDateTime.now();
        this.setFieldValByName("createTime", now, metaObject);
        this.setFieldValByName("updateTime", now, metaObject);
        this.setFieldValByName("deleteFlag", 0L, metaObject);
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if(authentication != null){
            if(authentication.getPrincipal() != null && authentication.getPrincipal() instanceof AuthUser){
                AuthUser user = (AuthUser) authentication.getPrincipal();
                this.setFieldValByName("creatorId", user.getId(), metaObject);
                this.setFieldValByName("updaterId", user.getId(), metaObject);
            }
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if(authentication != null){
            if(authentication.getPrincipal() != null && authentication.getPrincipal() instanceof AuthUser){
                AuthUser user = (AuthUser) authentication.getPrincipal();
                this.setFieldValByName("updaterId", user.getId(), metaObject);
            }
        }
    }

    @Override
    protected int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE + 10;
    }
}
